package com.test.cordova.util;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 读取本地asset 数据库文件
 * 使用方式
 *  1.在MainActivity 初始化 缓存db文件
  *     AssetsDBManager.initManager(this);
  *       // onRequestPermissionsResult  缓存本地db文件 权限处理
  *      AssetsDBManager.handleRequestPermission(requestCode,permissions,grantResults);
 *
 */

public class AssetsDBManager {

    private static final String TAG = AssetsDBManager.class.getSimpleName();
    private static Activity activity;
    private static AssetsDBManager instance = null;
    private static final int WRITE_EXTERNAL_CODE = 145;
    private static String[] dbNames = {"city.db"};
    private AssetsDBManager(Activity activity) {
        this.activity = activity;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_CODE);
            } else {
                cacheDBFiles(dbNames);
            }
        } else {
            cacheDBFiles(dbNames);
        }
    }

    /**
     * 缓存数据库
     * @param dbNames
     */
    private static void cacheDBFiles(String ... dbNames) {
        int length = dbNames.length;
        File cacheDirectory = StorageUtil.getCacheDirectory(activity);
        File db = null;
        for (int i = 0; i <  length; i++) {
             db = new File(cacheDirectory,dbNames[i]);
            if (db.exists()) {
                Logger.i(TAG,"已缓存");
                continue;
            } else {
                Logger.i(TAG,"去缓存");
                cacheDB(db);
            }
        }
    }

    private static void cacheDB(File db) {
        FileOutputStream out = null;
        InputStream in = null;
        try {
            out = new FileOutputStream(db);
            in = activity.getAssets().open(db.getName());
            byte[] buffer = new byte[1024];
            int readBytes = 0;
            while ((readBytes = in.read(buffer)) != -1)
                out.write(buffer, 0, readBytes);
            in.close();
            out.close();
            Logger.e(TAG,"缓存完成:"+db.getName());
        } catch (IOException e) {
            e.printStackTrace();
            Logger.e(TAG,"缓存:"+e.getMessage());
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void initManager(Activity activity) {
        if (instance == null) {
            instance = new AssetsDBManager(activity);
        }
    }

    public static AssetsDBManager getInstance() {
        return instance;
    }

    /**
     * 查询城市编号
     * @param areas
     * @return
     */
    public String queryCityDB(String ...areas){
        SQLiteDatabase db = getDB(dbNames[0]);
        if (db == null) {
            //db文件本地没缓存到 默认返回区域编码（广东省—广州市-市辖区）
            Logger.e(TAG,"result: db == null");
            return "DIAZ-ACCG-K7K3";
        }
        StringBuilder areaCode = new StringBuilder();
        String area_code = "";
        Cursor cursor = null;
        for (int i = 0; i < areas.length; i++) {
            cursor = db.query("area",null,"area_name = ?",new String[]{areas[i]},null,null,null);
            if (cursor.moveToFirst()) {
                area_code = cursor.getString(cursor.getColumnIndex("area_code"));
                if (i == areas.length-1) {
                    areaCode.append(area_code);
                } else {
                    areaCode.append(area_code).append("-");
                }
            }
        }
        if (cursor != null) {
            cursor.close();
            db.close();
        }
        area_code = null;
        cursor = null;
        db = null;
        Logger.i(TAG,"result: "+areaCode.toString());

        return areaCode.toString();
    }

    private SQLiteDatabase getDB(String dbName){
        File db = new File(StorageUtil.getCacheDirectory(activity),dbName);
        if (db.exists()) {
            //db 缓存本地权限通过
            return SQLiteDatabase.openOrCreateDatabase(new File(StorageUtil.getCacheDirectory(activity), dbName), null);
        } else {
            //db 缓存本地权限没有
            return null;
        }
    }

    /**
     * 处理请求权限
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public static void handleRequestPermission(int requestCode, String[] permissions, int[] grantResults){
        Logger.i(TAG,"handleRequestPermission");
        if (requestCode == WRITE_EXTERNAL_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            cacheDBFiles(dbNames);
        } else {
            Logger.e(TAG,"handleRequestPermission: denied caches");
        }
    }
}
